package com.thinkgem.jeesite.common.utils;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class WordToPDF {
	private static Logger logger = LoggerFactory.getLogger(DocUtil.class);
	static final int wdFormatPDF = 17;// PDF 格式  
	static final int xlFormatPDF = 0;//excel格式
	  
    public static void main(String[] args) {  
        WordToPDF.wordToPdf(null,"D:\\test.doc","D:\\test.pdf");  
    }  
    /**  
     * word转pdf  
     * @param fromAddress 待转文件地址  
     * @param toAddress 新文件地址  
     */  
    public static String wordToPdf(HttpServletRequest request,String fromAddress,String toAddress){  
    	ComThread.InitSTA();
        ActiveXComponent ax = null; 
        File tofile = new File(toAddress);  
        
        if (null != request) {
        	File savePath = new File(request.getSession().getServletContext().getRealPath("/")+"upload/outFile");
        	if (!savePath.exists()) {
        		savePath.mkdirs();
        	}
        	tofile = new File(savePath, toAddress);
		}
        if (tofile.exists()) {  
            tofile.delete();  
        }  
        try {  
            long startTime = System.currentTimeMillis();  
            /*  
             * 创建不同的控件调用不同的值  
             * Word——Word.Application  
             * Excel——Excel.Application  
             * Powerpoint——Powerpoint.Application  
             * Outlook——Outlook.Application  
             * */  
            ax = new ActiveXComponent("Word.Application");  
            /*设置打开word文档不可见*/  
            ax.setProperty("Visible", false);  
            //获取Word文档中所有内容  
            Dispatch docs = ax.getProperty("Documents").toDispatch();  
            //打开word文档，并设置word为不可编辑和不需确认  
            Dispatch doc = Dispatch.call(docs,  
                    "Open",   
                    fromAddress,// FileName  
                    false,// ConfirmConversions  
                    true // ReadOnly  
                    ).toDispatch();  
            //word文件另存为pdf文件  
            Dispatch.call(doc,//  
                    "SaveAs", //  
                    tofile.getAbsolutePath(), // FileName  
                    wdFormatPDF);  
            //关闭word文档  
            Dispatch.call(doc, "Close", false);  
            long endTime = System.currentTimeMillis();  
            System.out.println("转化完成,总共耗时" + (endTime - startTime) + "ms。");  
        } catch (Exception e) {  
        	e.printStackTrace();
        	logger.debug("转换出错!");
        	return "error:转换出错";
        } finally {  
            if (ax != null)  
                ax.invoke("Quit", new Variant[]{});  
            ComThread.Release();
        }  
        return tofile.getAbsolutePath();
    }  
    /**  
     * excel转pdf  
     * @param fromAddress 待转文件地址  
     * @param toAddress 新文件地址  
     */  
    public static String excelToPdf(HttpServletRequest request,String fromAddress,String toAddress){  
    	ComThread.InitSTA(true);
    	ActiveXComponent ax = null; 
    	File tofile = new File(toAddress);  
    	
    	if (null != request) {
    		File savePath = new File(request.getSession().getServletContext().getRealPath("/")+"upload/outFile");
    		if (!savePath.exists()) {
    			savePath.mkdirs();
    		}
    		tofile = new File(savePath, toAddress);
    	}
    	if (tofile.exists()) {  
    		tofile.delete();  
    	}  
    	try {  
    		long startTime = System.currentTimeMillis();  
    		/*  
    		 * 创建不同的控件调用不同的值  
    		 * Word——Word.Application  
    		 * Excel——Excel.Application  
    		 * Powerpoint——Powerpoint.Application  
    		 * Outlook——Outlook.Application  
    		 * */  
    		ax = new ActiveXComponent("Excel.Application");  
    		/*设置打开excel文档不可见*/  
    		ax.setProperty("Visible", false);  
    		ax.setProperty("AutomationSecurity", new Variant(3)); //禁用宏
    		//获取excel文档中所有内容  
    		Dispatch excels = ax.getProperty("Workbooks").toDispatch();  
    		//打开excel文档，并设置excel为不可编辑和不需确认  
    		/*Dispatch excel = Dispatch.call(excels,  
    				"Open",   
    				fromAddress,// FileName  
    				false,// ConfirmConversions  
    				true // ReadOnly  
    				).toDispatch();  
    		//excel文件另存为pdf文件  
    		Dispatch.call(excel, "ExportAsFixedFormat", xlFormatPDF, tofile.getAbsolutePath()); */
    		Dispatch excel=Dispatch.invoke(excels,"Open",Dispatch.Method,new Object[]{  
    	            fromAddress,  
    	            new Variant(false),  
    	            new Variant(false)  
    	        },  
    	        new int[9]).toDispatch();  
    	        //转换格式  
	        Dispatch.invoke(excel,"ExportAsFixedFormat",Dispatch.Method,new Object[]{  
	            new Variant(0), //PDF格式=0  
	            tofile.getAbsolutePath(),  
	            new Variant(0)  //0=标准 (生成的PDF图片不会变模糊) 1=最小文件 (生成的PDF图片糊的一塌糊涂)  
	        },new int[1]);  
    		//关闭excel文档  
    		Dispatch.call(excel, "Close", false);  
    		long endTime = System.currentTimeMillis();  
    		System.out.println("转化完成,总共耗时" + (endTime - startTime) + "ms。");  
    	} catch (Exception e) {  
    		e.printStackTrace();
    		logger.debug("转换出错!");
    		return "error:转换出错";
    	} finally {  
    		if (ax != null)  
    			ax.invoke("Quit", new Variant[]{});  
    		ComThread.Release();
    	}  
    	return tofile.getAbsolutePath();
    }  
    
    /**  
     * 打印pdf  
     * @param fromAddress 待转文件地址  
     */  
    public static String printPdf(String fromAddress){  
    	ComThread.InitSTA();
    	ActiveXComponent ax = null; 
    	try {  
    		/*  
    		 * 创建不同的控件调用不同的值  
    		 * Word——Word.Application  
    		 * Excel——Excel.Application  
    		 * Powerpoint——Powerpoint.Application  
    		 * Outlook——Outlook.Application  
    		 * */  
    		ax = new ActiveXComponent("Word.Application");  
    		/*设置打开word文档不可见*/  
    		ax.setProperty("Visible", false);  
    		//获取Word文档中所有内容  
    		Dispatch docs = ax.getProperty("Documents").toDispatch();  
    		//打开word文档，并设置word为不可编辑和不需确认  
    		Dispatch doc = Dispatch.call(docs,  
    				"Open",   
    				fromAddress,// FileName  
    				false,// ConfirmConversions  
    				true // ReadOnly  
    				).toDispatch();  
    		//打印
    		Dispatch.call(doc, "printOut");
    		//关闭word文档  
    		Dispatch.call(doc, "Close", false);  
    	} catch (Exception e) {  
    		e.printStackTrace();
    		logger.debug("转换出错!");
    		return "error:转换出错";
    	} finally {  
    		if (ax != null)  
    			ax.invoke("Quit", new Variant[]{});  
    		ComThread.Release();
    		/*File file = new File(fromAddress);
    		if (file.exists()) {
				file.delete();
			}*/
    	}  
    	return "打印成功";
    }  
}
